using SQLDMO;
using SQLServices.Repository;

namespace SQLRunnerDMO
{
	/// <summary>
	/// Simplified class version of a SQL DMO Database class
	/// </summary>
	public sealed class SQLDatabase: ISQLDBConn
	{

		#region Private Instances

		private readonly _Database _dmoDatabase;
		private readonly SQLConnection _sqlConnection;
		private readonly string _databaseName;

		#endregion
		#region Constructors

		public SQLDatabase(SQLConnection sqlConnection, string databaseName)
		{
			// Check if SQL Server instance is available
			_sqlConnection = sqlConnection;
			_databaseName = databaseName;
			_dmoDatabase = _sqlConnection.Database(_databaseName);
			
		}

		#endregion
		#region Properties
		
		public string DatabaseName
		{
			get { return _databaseName; }
		}

		public ISQLConnection SQLConnection
		{
			get { return _sqlConnection; }
		}

		#endregion
		#region Public Methods

		public ISQLDBConn Clone()
		{
			SQLConnection newConnection = new SQLConnection();
			newConnection.OpenConnection(_sqlConnection.ServerName,
				_sqlConnection.UserId, _sqlConnection.Password, _sqlConnection.LoginSecure);
			return new SQLDatabase(newConnection, _databaseName);
		}

		public void Execute(string sqlScript)
		{
			_dmoDatabase.ExecuteImmediate(
				sqlScript, SQLDMO_EXEC_TYPE.SQLDMOExec_Default, sqlScript.Length);
		}

        public long GetTranCount()
        {
            string sqlScript = "SELECT @@TranCount";
            QueryResults results = _dmoDatabase.ExecuteWithResults(sqlScript, sqlScript.Length);
            if (results == null) return -1;
            return results.GetColumnLong(1, 1);
        }

	    public string GetToken()
	    {
            string sqlScript = "DECLARE @token varchar(255) " +
	                           "exec sp_getbindtoken @token output " +
	                           "Select @token token";
            QueryResults results = _dmoDatabase.ExecuteWithResults(sqlScript, sqlScript.Length);
            if (results == null) return null;
            return results.GetColumnString(1, 1);
	    }

	    #region ISQLDBConn Members

	    public void SetToken(string token)
	    {
            string sqlScript = string.Format("exec sp_bindsession '{0}'", token);
            _dmoDatabase.ExecuteImmediate(sqlScript, SQLDMO_EXEC_TYPE.SQLDMOExec_Default, sqlScript.Length);
	    }

	    #endregion

	    #endregion

	}
}
